<?php
namespace app\middleware;

use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;

class CorsMiddleware implements MiddlewareInterface
{
    public function process(Request $request, callable $next): Response
    {
        // 处理OPTIONS预检请求
        if ($request->method() === 'OPTIONS') {
            $response = response('', 204);
        } else {
            try {
                $response = $next($request);
            } catch (\Throwable $e) {
                $response = response()->json([
                    'code' => $e->getCode(),
                    'msg'  => $e->getMessage()
                ], 500);
            }
        }

        // 动态设置允许的源（支持多域名）
        $allowedOrigins = [
            'http:///192.168.1.3:8080',
        ];
        $origin = $request->header('origin');
        $allowOrigin = in_array($origin, $allowedOrigins) ? $origin : '*';

        // 设置跨域头
        $headers = [
            'Access-Control-Allow-Origin'      => $allowOrigin,
            'Access-Control-Allow-Credentials' => 'true',
            'Access-Control-Max-Age'           => 86400,
            'Access-Control-Allow-Methods'     => 'GET, POST, PUT, DELETE, OPTIONS',
            'Access-Control-Allow-Headers'     => $request->header(
                'Access-Control-Request-Headers',
                'Content-Type, Authorization, X-Requested-With, X-Token'
            )
        ];

        // 添加Vary头避免缓存问题
        if ($allowOrigin !== '*') {
            $headers['Vary'] = 'Origin';
        }

        return $response->withHeaders($headers);
    }
}